import React, { SyntheticEvent, useState } from 'react';
import Image from 'next/image';
import { omitData } from '@/utils/common';

type ImageType = typeof Image;
// @ts-ignore
const MyImage: ImageType<{ onNewSrc?: Fn }> = props => {
  const {
    src,
    alt = '',
    onNewSrc,
    className = '',
    isImgTag = true,
    ...restProps
  } = props;
  const [imgUrl, setImgUrl] = useState<string>(src as string);
  const [isSuccess, setIsSuccess] = useState<boolean>(false);

  const handleLoad = () => {
    setIsSuccess(true);
  };

  const handleImageError = (e: SyntheticEvent<HTMLImageElement, Event>) => {
    // gcpdev -> cdn -> placeholder image
    if (imgUrl.includes('product-holder.png')) return;

    if (imgUrl.includes('//cdn')) {
      setImgUrl(location.origin + '/nextasset/images/product-holder.png');
      return;
    }

    const newUrl = imgUrl.replace('//gcpdev.', '//cdn.');
    setImgUrl(newUrl);
    if (onNewSrc) onNewSrc(newUrl);
  };

  // in production env, use cdn link is better
  // so use the origin <img> tag instead of next/image
  const isProd = process.env.NEXT_PUBLIC_APP_ENV === 'production';

  return isProd || isImgTag ? (
    // eslint-disable-next-line @next/next/no-img-element
    <img
      alt={alt}
      src={imgUrl}
      data-src={src}
      onError={handleImageError}
      onLoad={handleLoad}
      className={`my-image ${className} ${restProps.fill ? 'my-image-fill' : ''} ${isSuccess ? 'my-image-success' : ''}`}
      {...omitData(restProps, ['fill', 'priority', 'className'])}
    />
  ) : (
    <Image
      data-src={src}
      alt={alt}
      src={imgUrl}
      onError={handleImageError}
      onLoad={handleLoad}
      className={`my-image ${className} ${isSuccess ? 'my-image-success' : ''}`}
      {...restProps}
    />
  );
};

export default MyImage;
